
import 'package:flutter/material.dart';
import 'package:qaun_ni_dev/provider/rongImProvider.dart';
import 'package:qaun_ni_dev/im/pages/conversation_list_page.dart';

import 'package:provider/provider.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

import 'widget_util.dart';

import '../../util/style.dart';
import '../../util/time.dart';
import '../../util/user_info_datesource.dart';


abstract class ConversationListItemDelegate {
  ///点击了会话 item
  void didTapConversation(Conversation conversation);
  ///长按了会话 item
  void didLongPressConversation(Conversation conversation,Offset tapPos);
}

class ConversationListItemWidget extends StatefulWidget {
  final Conversation conversation;
  ConversationListItemWidget({Key key,this.conversation}):super(key:key);

  @override
  _ConversationListItemWidgetState createState() => _ConversationListItemWidgetState(this.conversation);
}

class _ConversationListItemWidgetState extends State<ConversationListItemWidget> {
  Conversation conversation ;
  BaseInfo info;
  Offset tapPos;

  _ConversationListItemWidgetState(Conversation con) {
    this.conversation = con;
    if(con.conversationType == RCConversationType.Private){
      this.info = UserInfoDataSource.getUserInfo(con.targetId);
    }
  }


  @override
  void initState() {
    super.initState();
  }

  void _deleteConversation(context,Conversation conversation) {
    //删除会话需要刷新会话列表数据
    RongcloudImPlugin.removeConversation(conversation.conversationType, conversation.targetId, (bool success) {
      if(success) {
        RongcloudImPlugin.deleteMessages(conversation.conversationType, conversation.targetId, (int code) {
        });
      }
      Navigator.push(context,MaterialPageRoute(
        builder: (context) => ConversationListPage()
      ));
    });
  }

  /** 02-25 清空会话未读数之后，重新获取所有未读数，更新数据  **/
  void _clearConversationUnread(context,Conversation conversation) async {
    //清空未读需要刷新会话列表数据
    bool success = await RongcloudImPlugin.clearMessagesUnreadStatus(conversation.conversationType, conversation.targetId);
    if(success) {
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Color(RCColor.ConListItemBgColor),
      child: InkWell(
        onTapDown: (TapDownDetails details) {https://github.com/flutter/plugins/tree/master/packages/firebase_messaging
          tapPos = details.globalPosition;
        },
        onTap: () {
            Map arg = {"coversationType":conversation.conversationType,"targetId":conversation.targetId};
            Navigator.pushNamed(context, "/conversation",arguments: arg);
            RongcloudImPlugin.clearMessagesUnreadStatus(conversation.conversationType,conversation.targetId);
            print('${conversation.conversationType}---${conversation.targetId}');
            Provider.of<RongImProvider>(context,listen: false).getConversionList();
            print('点击的时候，清除该会话的未读数');
        },
        onLongPress: () {
//          if(this.delegate != null) {
//            this.delegate.didLongPressConversation(this.itemData,this.tapPos);
            Map<String,String> actionMap = {
              RCLongPressAction.DeleteConversationKey:RCLongPressAction.DeleteConversationValue,
              RCLongPressAction.ClearUnreadKey:RCLongPressAction.ClearUnreadValue
            };
            WidgetUtil.showLongPressMenu(context, tapPos,actionMap,(String key) {
              print("当前选中的是 "+ key);
              if(key == RCLongPressAction.DeleteConversationKey) {
                _deleteConversation(context,conversation);
              }else if(key == RCLongPressAction.ClearUnreadKey) {
                _clearConversationUnread(context,conversation);
              }else {
                print("未实现操作 "+key);
              }
            });
            Provider.of<RongImProvider>(context,listen: false).getConversionList();
//          }else {
//            print("没有实现 ConversationListItemDelegate");
//          }
        },
        child: Container(
          height: RCLayout.ConListItemHeight,
          color: Color(RCColor.ConListItemBgColor),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              _buildPortrait(),
              _buildContent()
            ],
          ),
        ),
      ),
    );
  }


  Widget _buildPortrait() {
    return Stack(
      overflow: Overflow.visible,
      children: <Widget>[
        Row(
          children: <Widget>[
            SizedBox(
              width: 8,
            ),
            WidgetUtil.buildUserPortrait(this.info.portraitUrl),
          ],
        ),
        Positioned(
          right:-3.0 ,
          top: -3.0,
          child: _buildUnreadCount(conversation.unreadMessageCount),
        ),
      ],
    );
  }

  Widget _buildContent(){
    return Expanded(
      child: Container(
        height: RCLayout.ConListItemHeight,
        margin: EdgeInsets.only(left:8),
        decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(width: 0.5,color: Color(RCColor.ConListBorderColor),)
            )
        ),
        child: Row(
          children: <Widget>[
            _buildTitle(),
            _buildTime()
          ],
        ),
      ),
    );
  }

  Widget _buildTime(){
    String time = TimeUtil.convertTime(conversation.sentTime);
    List<Widget> _rightArea =<Widget>[
      Text(time,style:TextStyle(fontSize: RCFont.ConListTimeFont,color: Color(RCColor.ConListTimeColor))),
      SizedBox(height: 15,)
    ];
    return Container(
      width:RCLayout.ConListItemHeight,
      margin: EdgeInsets.only(right: 8),
      child: Column(
          mainAxisAlignment:  MainAxisAlignment.center,
          children: _rightArea
      ),
    );
  }

  Widget _buildTitle(){
    String title = this.info.name;
    String digest = "";
    if(conversation.latestMessageContent != null) {
      digest = conversation.latestMessageContent.conversationDigest();
    }
    if(digest == null) {
      digest = "";
    }
    return Expanded(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            title,
            style: TextStyle(fontSize: RCFont.ConListTitleFont,color: Color(RCColor.ConListTitleColor),fontWeight:FontWeight.w400),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          SizedBox(height: 6,),
          Text(
            digest,
            style: TextStyle(fontSize: RCFont.ConListDigestFont,color: Color(RCColor.ConListDigestColor)),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          )
        ],
      ),
    );
  }

  Widget _buildUnreadCount(int count) {
    if(count <=0 || count == null) {
      return WidgetUtil.buildEmptyWidget();
    }
    return Container(
        width: RCLayout.ConListUnreadSize,
        height: RCLayout.ConListUnreadSize,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(RCLayout.ConListUnreadSize/2.0),
            color: Color(RCColor.ConListUnreadColor)
        ),
        child: count > 99 ? Text('...',style:TextStyle(fontSize: RCFont.ConListUnreadFont,color: Color(RCColor.ConListUnreadTextColor))) : Text(count.toString(),style:TextStyle(fontSize: RCFont.ConListUnreadFont,color: Color(RCColor.ConListUnreadTextColor)))
    );
  }




}
